import { login, logout, getInfo, register } from '@/api/user'
import { getToken, setToken, setRoles, removeToken, removeRoles, setId, getId, removeId } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    roles: [],
    name: '',
    avatar: '',
    number: '',
    password: '',
    signature: '',
    age: '',
    gender: '',
    colleges: '',
    email: '',
    phone: '',
    hobbies: '',
    registrationDate: '',
    id: null
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_NUMBER: (state, number) => {
    state.number = number
  },
  SET_PASSWORD: (state, password) => {
    state.password = password
  },
  SET_SIGNATURE: (state, signature) => {
    state.signature = signature
  },
  SET_AGE: (state, age) => {
    state.age = age
  },
  SET_GENDER: (state, gender) => {
    state.gender = gender
  },
  SET_COLLEGES: (state, colleges) => {
    state.colleges = colleges
  },
  SET_EMAIL: (state, email) => {
    state.email = email
  },
  SET_PHONE: (state, phone) => {
    state.phone = phone
  },
  SET_HOBBIES: (state, hobbies) => {
    state.hobbies = hobbies
  },
  SET_REGISTRATIONDATE: (state, registrationDate) => {
    state.registrationDate = registrationDate
  },
  SET_ID: (state, id) => {
    console.log(id)
    state.id = id
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    console.log(userInfo)
    if (userInfo.roles === 'USER') {
      login({ userName: username, userPassword: password, Roles: userInfo.roles }, userInfo.roles).then(response => {
        console.log(response)
        console.log(response.data.token)
        commit('SET_TOKEN', response.data.token)
        commit('SET_ROLES', [userInfo.roles])
        commit('SET_ID', response.data.user.userId)
        setToken(response.data.token)
        // 设置Cookie的Token和Roles
        setRoles(userInfo.roles)
        setId(response.data.user.userId)
      }).catch(res => {
        console.log('cuowu')
      })
    }
    if (userInfo.roles === 'ADMIN') {
      login({ adminAccount: username, adminPassword: password, Roles: userInfo.roles }, userInfo.roles).then(response => {
        console.log(response)
        console.log(response.data.token)
        commit('SET_TOKEN', response.data.token)
        commit('SET_ROLES', [userInfo.roles])
        commit('SET_ID', response.data.admin.adminId)
        setToken(response.data.token)
        // 设置Cookie的Token和Roles
        setRoles(userInfo.roles)
        setId(response.data.admin.adminId)
      }).catch(res => {
        console.log('cuowu')
      })
    }
    if (userInfo.roles === 'SUPER_ADMIN') {
      login({ suAdminAccount: username, suAdminPassword: password }, userInfo.roles).then(response => {
        console.log(response)
        console.log(response.data.token)
        commit('SET_TOKEN', response.data.token)
        commit('SET_ROLES', [userInfo.roles])
        commit('SET_ID', response.data.suadmin.suAdminId)
        setToken(response.data.token)
        // 设置Cookie的Token和Roles
        setRoles(userInfo.roles)
        setId(response.data.suadmin.suAdminId)
      }).catch(res => {
        console.log('cuowu123')
      })
    }
  },

  register({ commit }, userInfo) {
    const data = userInfo
    console.log(data)
    register({
      'userName': data.name, // 用户名
      'userType': 'USER', // 用户类型
      'userPassword': data.pwd, // 密码
      'userCollege': data.colloge,
      'studentId': data.sid, // 学号
      // 手机号暂时设置位空，由用户登陆后自己设置。
      'userPhonenumber': '' // 手机号
    }).then(response => {
      console.log(data.name, data.name)
      const { data } = response
      commit('SET_TOKEN', data.userName)
    }).catch(res => {
      console.log('cuowu')
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const {
          roles,
          name,
          avatar,
          number,
          password,
          colleges,
          phone,
          hobbies
        } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_NUMBER', number)
        commit('SET_PASSWORD', password)
        commit('SET_COLLEGES', colleges)
        commit('SET_PHONE', phone)
        commit('SET_HOBBIES', hobbies)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    commit('SET_TOKEN', '')
    commit('SET_ROLES', [])
    commit('SET_Id', '')
    removeToken()
    removeId()
    resetRouter()
    removeRoles()
    // reset visited views and cached views
    // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
    dispatch('tagsView/delAllViews', null, { root: true })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },
  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

